<script setup lang="ts">
import {type RouteRecord,useRouter} from 'vue-router'
import {routes} from "@/router";

console.log('routes---->', routes)
const defaultProps = {
  children: 'children',
  label: 'name',
}

interface Node {
  id: number,
  data: {
    name: string,
    path: string,
  },
  parent: Node
}

//获取所有的父级路径
function getParentPath(node: Node): Array<string> {
  if (!node.id) {
    return [];
  }
  let arr = [node.data.path];
  if (node.parent) {
    let res = getParentPath(node.parent);
    if (res) arr = res.concat(arr);
  }
  return arr;
}
//组装路径
const getPath = (node: Node): string => {
  const list = getParentPath(node);
  let path = '';
  for (let i = 0, len = list.length; i < len; i++) {
    let cur = list[i];
    if (cur.startsWith('/')) {
      path = cur;
      continue;
    }
    if (cur.endsWith('/')) {
      cur = cur.substring(0, cur.length - 1);
    }
    path += '/' + cur;
  }
  return path;
}

const router=useRouter();
const handleNodeClick = (data: RouteRecord, node:Node, b:any, c:any) => {
  const path=getPath(node);
  if (path) {
    router.push(path);
  }
}


</script>

<template>
  <el-tree
      style="max-width: 600px"
      :data="routes"
      :props="defaultProps"
      @node-click="handleNodeClick"
  />
</template>

<style scoped>

</style>